package frame.PayMain;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import frame.PayMain.PayMainPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.EmployeeMapper;
import org.example.mapper.GoodMapper;
import org.example.mapper.PayDetailMapper;
import org.example.mapper.PayMainMapper;
import org.example.pojo.Employee;
import org.example.pojo.Good;
import org.example.pojo.PayDetail;
import org.example.pojo.PayMain;
import org.jdesktop .swingx.JXDatePicker;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class PayMainAddPanel extends JInternalFrame {
    private JComboBox<String> eidComboBox; // 员工编号下拉框
    private JXDatePicker pdatePicker; // 采购时间日期选择器
    private JTextField remarkField; // 备注文本框
    private JTable detailTable; // 明细表格
    private DefaultTableModel detailTableModel; // 明细表格模型
    private JTextField totalQuantityField; // 总数量文本框
    private JTextField totalPriceField; // 总价格文本框
    private SqlSession sqlSession; // MyBatis SqlSession
    private PayMainMapper payMainMapper; // PayMain Mapper
    private PayDetailMapper payDetailMapper; // PayDetail Mapper
    private EmployeeMapper employeeMapper; // Employee Mapper
    private GoodMapper goodMapper; // Good Mapper

    public PayMainAddPanel() {
        setTitle("添加采购记录");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

        // 初始化SqlSession和Mappers
        try {
            sqlSession = MyBatislianjian.getSqlSession();
            if (sqlSession == null) throw new IllegalStateException("sqlSession为空");
            payMainMapper = sqlSession.getMapper(PayMainMapper.class);
            if (payMainMapper == null) throw new IllegalStateException("payMainMapper为空");
            payDetailMapper = sqlSession.getMapper(PayDetailMapper.class);
            if (payDetailMapper == null) throw new IllegalStateException("payDetailMapper为空");
            employeeMapper = sqlSession.getMapper(EmployeeMapper.class);
            if (employeeMapper == null) throw new IllegalStateException("employeeMapper为空");
            goodMapper = sqlSession.getMapper(GoodMapper.class);
            if (goodMapper == null) throw new IllegalStateException("goodMapper为空");
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "初始化Mapper时出错：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
            return;
        }

        // 添加主要采购信息面板
        JPanel mainPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.anchor = GridBagConstraints.WEST;
        gbc.gridx = 0;
        gbc.gridy = 0;
        mainPanel.add(new JLabel("员工编号:"), gbc);

        // 初始化和填充员工编号下拉框
        eidComboBox = new JComboBox<>();
        populateEidComboBox();
        gbc.gridx = 1;
        mainPanel.add(eidComboBox, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        mainPanel.add(new JLabel("采购时间:"), gbc);

        gbc.gridx = 1;
        pdatePicker = new JXDatePicker();
        pdatePicker.setFormats("yyyy-MM-dd");
        pdatePicker.setDate(new Date());
        mainPanel.add(pdatePicker, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        mainPanel.add(new JLabel("备注:"), gbc);

        gbc.gridx = 1;
        remarkField = new JTextField(20);
        mainPanel.add(remarkField, gbc);

        // 添加总数量和总价格字段
        gbc.gridx = 0;
        gbc.gridy++;
        mainPanel.add(new JLabel("采购总量:"), gbc);

        gbc.gridx = 1;
        totalQuantityField = new JTextField(10);
        totalQuantityField.setEditable(false); // 此字段不可由用户编辑
        mainPanel.add(totalQuantityField, gbc);

        gbc.gridx = 0;
        gbc.gridy++;
        mainPanel.add(new JLabel("采购总价:"), gbc);

        gbc.gridx = 1;
        totalPriceField = new JTextField(10);
        totalPriceField.setEditable(false); // 此字段不可由用户编辑
        mainPanel.add(totalPriceField, gbc);

        // 将主面板添加到内部框架的顶部
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(mainPanel, BorderLayout.NORTH);

        // 添加采购明细面板
        detailTableModel = new DefaultTableModel() {
            @Override
            public boolean isCellEditable(int row, int column) {
                // 允许编辑数量和备注列
                return column == 1 || column == 4;
            }
        };
        detailTable = new JTable(detailTableModel);

        // 添加表头
        String[] columnNames = {"商品编号", "采购数量", "采购单价", "小计", "备注"};
        detailTableModel.setColumnIdentifiers(columnNames);

        // 启用表格编辑并设置自动调整模式
        detailTable.setEnabled(true);
        detailTable.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        JScrollPane detailScrollPane = new JScrollPane(detailTable);

        // 将明细表格添加到内部框架的中心
        getContentPane().add(detailScrollPane, BorderLayout.CENTER);

        // 初始化下拉框或字段
        populateDetailTable();

        // 添加监听器以在数量更改时更新小计
        detailTableModel.addTableModelListener(e -> {
            int row = e.getFirstRow();
            int column = e.getColumn();
            if (column == 1 || column == 2) { // 数量或单价列
                updateSubtotal(row);
                updateTotalFields(); // 更新总数量和总价格字段
            }
        });

        // 添加按钮
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                addPurchaseRecord();
            }
        });

        JButton returnButton = new JButton("返回");
        returnButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new PayMainPanel());
            }
        });

        buttonPanel.add(addButton);
        buttonPanel.add(returnButton);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        setSize(800, 600);
        setVisible(true);
    }

    private List<PayDetail> extractPayDetailsFromTable() {
        List<PayDetail> payDetails = new ArrayList<>();
        for (int row = 0; row < detailTableModel.getRowCount(); row++) {
            String gid = (String) detailTableModel.getValueAt(row, 0);
            String pcountStr = (String) detailTableModel.getValueAt(row, 1);
            String gpayStr = String.valueOf(detailTableModel.getValueAt(row, 2));
            String totalStr = (String) detailTableModel.getValueAt(row, 3);
            String other = (String) detailTableModel.getValueAt(row, 4);

            if (!pcountStr.isEmpty()) {
                int pcount = Integer.parseInt(pcountStr);
                float gpay = Float.parseFloat(gpayStr);
                float total = totalStr.isEmpty() ? 0.0f : Float.parseFloat(totalStr);

                PayDetail payDetail = new PayDetail(null, gid, pcount, gpay, total, other);
                payDetails.add(payDetail);
            }
        }
        return payDetails;
    }

    private void populateEidComboBox() {
        List<Employee> employees = employeeMapper.selectAll();
        for (Employee employee : employees) {
            eidComboBox.addItem(employee.getEid());
        }
    }

    private void populateDetailTable() {
        List<Good> goods = goodMapper.selectAll();
        for (Good good : goods) {
            detailTableModel.addRow(new Object[]{good.getGid(), "", good.getGPay(), "", ""});
        }
    }

    private void updateSubtotal(int row) {
        String quantityStr = (String) detailTableModel.getValueAt(row, 1);
        String unitPriceStr = String.valueOf(detailTableModel.getValueAt(row, 2));

        if (quantityStr.isEmpty() || unitPriceStr.isEmpty()) {
            detailTableModel.setValueAt("", row, 3); // 如果数量或单价为空，则将小计设置为空
            return;
        }

        int quantity = Integer.parseInt(quantityStr);
        float unitPrice = Float.parseFloat(unitPriceStr);
        float subtotal = quantity * unitPrice;

        // 格式化小计为两位小数
        detailTableModel.setValueAt(String.format("%.2f", subtotal), row, 3);
    }

    private void updateTotalFields() {
        int totalQuantity = 0;
        float totalPrice = 0.0f;

        for (int row = 0; row < detailTableModel.getRowCount(); row++) {
            String quantityStr = (String) detailTableModel.getValueAt(row, 1);
            String subtotalStr = (String) detailTableModel.getValueAt(row, 3);

            if (!quantityStr.isEmpty()) {
                totalQuantity += Integer.parseInt(quantityStr);
            }
            if (!subtotalStr.isEmpty()) {
                totalPrice += Float.parseFloat(subtotalStr);
            }
        }

        totalQuantityField.setText(String.valueOf(totalQuantity));
        totalPriceField.setText(String.format("%.2f", totalPrice));
    }

    private void addPurchaseRecord() {
        String eid = (String) eidComboBox.getSelectedItem(); // 员工编号
        Date pdate = pdatePicker.getDate(); // 获取采购时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String pdateStr = sdf.format(pdate); // 格式化日期
        String remark = remarkField.getText().trim(); // 备注
        int totalQuantity = Integer.parseInt(totalQuantityField.getText()); // 总量
        float totalPrice = Float.parseFloat(totalPriceField.getText()); // 总价

        // 提取明细信息并封装成PayDetail对象列表
        List<PayDetail> payDetails = extractPayDetailsFromTable();
        PayMain payMain = new PayMain(eid, totalQuantity, totalPrice, pdateStr, remark);

        if (eid.isEmpty() || pdate == null) {
            JOptionPane.showMessageDialog(this, "员工编号和采购时间不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 插入采购主记录
        payMainMapper.addPayMain(payMain);

        // 获取刚插入的Pid
        Integer lastPid = payMain.getPid();

        // 插入采购明细记录
        for (PayDetail payDetail : payDetails) {
            payDetail.setPid(lastPid);
            payDetailMapper.addPayDetail(payDetail);
        }
        JOptionPane.showMessageDialog(this, "添加成功", "提示", JOptionPane.INFORMATION_MESSAGE);
    }
}
